package com.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.pojo.Product;
import com.utils.JDBCDBCPUtils;

public class ProductDao {
	QueryRunner qr=new QueryRunner(JDBCDBCPUtils.getDataSource());

	public List<Product> findAll(String condition,Object[] params){
		String sql="select *from product where 1=1 " +condition +" limit ?,?";
		System.out.println(sql);
		System.out.println(Arrays.toString(params));
		List<Product> list =null;
		try {
		list = qr.query(sql, new BeanListHandler<Product>(Product.class),params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return  list;
	}

	public Product findProductByPid(int pid) {
		String sql="select *from product where pid=? ";
		Product product =null;
		try {
			product = qr.query(sql, new BeanHandler<Product>(Product.class),pid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return  product;
	}

	public Integer findAllProductCount() {
		String sql="select count(*) from product";
		Long count=0L;
		try {
			 count = qr.query(sql, new ScalarHandler<Long>());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count.intValue();
	}

	public List<Product> findallByWordPname(String word) {
		String sql="select *from product where  pname like ? " ;
		List<Product> list =null;
		try {
		list = qr.query(sql, new BeanListHandler<Product>(Product.class),"%"+word+"%");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return  list;
	}
}
